package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 * 
 * @author zzyl
 * @date 2025-10-16
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     *
     * @param checkInApplyDto
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInApplyDto) {
        // 判断老人是否已经入住
        // 通过身份证号查询老人
        LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper<Elder>();
        //看dto中的身份证号是否等于老人的身份证号
        elderQueryWrapper.eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo());
        elderQueryWrapper.eq(Elder::getStatus, 1);
        //查看老人是否入住
        Elder elder =  elderMapper.selectOne(elderQueryWrapper);
        if(ObjectUtils.isNotEmpty(elder)) {
            throw new BaseException("老人已入住");
        }

        // 更新床位的状态  已入住
        Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        // 保存或更新老人数据
        elder = insertOrUpdateElder(bed, checkInApplyDto.getCheckInElderDto());

        // 生成合同编号
        String contractNo = "HT" + CodeGenerator.generateContractNumber();

        // 新增签约办理
        insertContract(contractNo, elder, checkInApplyDto);

        // 新增入住信息
        CheckIn checkIn = insertCheckIn(elder, checkInApplyDto);

        // 新增入住配置信息
        insertCheckInConfig(checkIn.getId(), checkInApplyDto);
    }



    /**
     * 新增入住配置
     * @param checkInApplyDto
     */
    private void insertCheckInConfig(Long checkInId, CheckInApplyDto checkInApplyDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkInId);
/*        bug
        // 手动设置默认值
        if (checkInConfig.getFeeStartDate() == null) {
            checkInConfig.setFeeStartDate(new Date());
        }*/
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     * @param elder
     * @param checkInApplyDto
     */
    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn;
    }
//    另一种
    private void saveCheckIn(CheckInApplyDto dto,Elder elder) {
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        CheckIn checkIn = BeanUtil.toBean(checkInConfigDto,CheckIn.class);
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
    }

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 新增合同
     * @param contractNo
     * @param elder
     * @param checkInApplyDto
     */
    private void insertContract(String contractNo, Elder elder, CheckInApplyDto checkInApplyDto) {

        Contract contract = new Contract();
        // 属性拷贝
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        contract.setContractNumber(contractNo);
        contract.setElderId(Math.toIntExact(elder.getId()));
        contract.setElderName(elder.getName());
        // 状态、开始时间、结束时间
        // 签约时间小于等于当前时间，合同生效中
        LocalDateTime checkInStartTime = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime checkInEndTime = checkInApplyDto.getCheckInConfigDto().getEndDate();
        Integer status = checkInStartTime.isBefore(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(status);
        contract.setStartDate(checkInStartTime);
        contract.setEndDate(checkInEndTime);
        contractMapper.insert(contract);
    }

    /**
     * 新增或更新老人
     * @param bed
     * @param checkInElderDto
     * @return
     */
    private Elder insertOrUpdateElder(Bed bed, CheckInElderDto checkInElderDto) {

        // 准备老人数据
        Elder elder = new Elder();
        // 属性拷贝
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elder.setStatus(1);
        // 查询老人信息，（身份证号、状态不为1）
        LambdaQueryWrapper<Elder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo()).ne(Elder::getStatus, 1);
        Elder elderDb =  elderMapper.selectOne(lambdaQueryWrapper);
        if(ObjectUtils.isNotEmpty(elderDb)) {
            // 修改
            elderMapper.updateById(elder);
        }else {
            // 新增
            elderMapper.insert(elder);
        }
        return elder;
    }
    /**
     * 获取入住详情 最后一个接口
     *
     * @param id 入住主键
     * @return 入住详情
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        // 1. 查询入住信息
        CheckIn checkIn = selectCheckInById(id);
        if (checkIn == null) {
            return null;
        }

        // 2. 查询老人信息
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        if (elder == null) {
            return null;
        }

        // 3. 通过老人ID查询合同信息
        Contract contract = null;
        LambdaQueryWrapper<Contract> contractWrapper = new LambdaQueryWrapper<>();
        contractWrapper.eq(Contract::getElderId, Math.toIntExact(elder.getId()));
        contract = contractMapper.selectOne(contractWrapper);

        // 4. 查询入住配置信息 - 修正查询条件
        CheckInConfig checkInConfig = null;
        LambdaQueryWrapper<CheckInConfig> configWrapper = new LambdaQueryWrapper<>();
        configWrapper.eq(CheckInConfig::getCheckInId, checkIn.getId());
        checkInConfig = checkInConfigMapper.selectOne(configWrapper);

        // 5. 转换家属列表
        List<ElderFamilyVo> elderFamilyVoList = convertFamilyList(checkIn.getRemark());

        // 6. 整合数据返回
        CheckInDetailVo detailVo = new CheckInDetailVo();

        // 设置老人信息
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        checkInElderVo.setId(elder.getId());
        checkInElderVo.setName(elder.getName());
        checkInElderVo.setIdCardNo(elder.getIdCardNo());
        checkInElderVo.setBirthday(elder.getBirthday());
        checkInElderVo.setSex(elder.getSex());
        checkInElderVo.setPhone(elder.getPhone());
        checkInElderVo.setAddress(elder.getAddress());
        checkInElderVo.setImage(elder.getImage());
        checkInElderVo.setIdCardNationalEmblemImg(elder.getIdCardNationalEmblemImg());
        checkInElderVo.setIdCardPortraitImg(elder.getIdCardPortraitImg());
        checkInElderVo.setAge(calculateAge(elder.getBirthday()));
        detailVo.setCheckInElderVo(checkInElderVo);
        detailVo.setElderFamilyVoList(elderFamilyVoList);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        if (checkInConfig != null) {
            BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        }
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        detailVo.setCheckInConfigVo(checkInConfigVo);
        detailVo.setContract(contract);
        return detailVo;
    }


    /**
     * 转换家属列表
     *
     * @param remark 家属信息JSON字符串
     * @return 家属列表
     */
    private List<ElderFamilyVo> convertFamilyList(String remark) {
        if (remark == null || remark.isEmpty()) {
            return new ArrayList<>();
        }

        try {
            List<ElderFamilyDto> familyDtos = JSON.parseArray(remark, ElderFamilyDto.class);
            List<ElderFamilyVo> familyVos = new ArrayList<>();

            for (ElderFamilyDto dto : familyDtos) {
                ElderFamilyVo vo = new ElderFamilyVo();
                vo.setName(dto.getName());
                vo.setPhone(dto.getPhone());
                vo.setKinship(dto.getKinship());
                familyVos.add(vo);
            }

            return familyVos;
        } catch (Exception e) {
            // 修正日志输出
            log.error("转换家属列表失败: {}");
            return new ArrayList<>();
        }
    }


    /**
     * 计算年龄
     *
     * @param birthday 出生日期
     * @return 年龄
     */
    private Integer calculateAge(String birthday) {
        if (birthday == null || birthday.isEmpty()) {
            return null;
        }

        try {
            LocalDate birthDate = LocalDate.parse(birthday);
            LocalDate now = LocalDate.now();
            return Period.between(birthDate, now).getYears();
        } catch (Exception e) {
            log.error("计算年龄失败: {}");
            return null;
        }
    }

}
